//package com.scnu.hachimi.manager;
//
//import javax.imageio.ImageIO;
//import java.awt.*;
//import java.awt.image.BufferedImage;
//import java.io.File;
//import java.io.IOException;
//import java.nio.file.*;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.stream.Stream;
//
//public class ResourcesManager {
//    public Map<String, Image> imageMap = new HashMap<>();
//
//    public ResourcesManager(String directoryPath) {
//        try {
//            loadImages(directoryPath);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    public Map<String, Image> loadImages(String directoryPath) throws IOException {
//        Path startPath = Paths.get(directoryPath);
//
//        Files.walk(startPath)
//                .filter(Files::isRegularFile)
//                .forEach(path -> {
//                    try {
//                        String fileName = path.getFileName().toString();
//                        int dotIndex = fileName.lastIndexOf('.');
//                        if (dotIndex != -1) {
//                            String fileExtension = fileName.substring(dotIndex + 1).toLowerCase();
//                            if (isValidImageExtension(fileExtension)) {
//                                String key = fileName.substring(0, dotIndex);
//                                Image image = ImageIO.read(path.toFile());
//                                imageMap.put(key, image);
//                            }
//                        }
//                    } catch (IOException e) {
//                        System.err.println("Error loading image: " + path);
//                        e.printStackTrace();
//                    }
//                });
//        return imageMap;
//    }
//
//    private boolean isValidImageExtension(String extension) {
//        // 可以根据需要添加更多的图片格式
//        return extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png") || extension.equals("gif") || extension.equals("bmp");
//    }
//
////    public static void main(String[] args) {
////        ResourcesManager resourceManager = new ResourcesManager();
////        try {
////            // 替换为你的目标目录路径
////            String directoryPath = "image";
////            Map<String, Image> images = resourceManager.loadImages(directoryPath);
////            System.out.println("Loaded " + images.size() + " images.");
////            for (Map.Entry<String, Image> entry : images.entrySet()) {
////                System.out.println("Image: " + entry.getKey());
////                // 可以在这里对图片进行进一步处理
////            }
////            // 在这里可以使用 images 进行其他操作
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
//
////    }
//}

package com.scnu.hachimi.manager;

import javax.imageio.ImageIO;
import java.awt.Image;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ResourcesManager {
    public Map<String, Image> imageMap = new HashMap<>();

    public ResourcesManager(String resourcePath) {
        try {
            // 确保路径以斜杠开头
            if (!resourcePath.startsWith("/")) {
                resourcePath = "/" + resourcePath;
            }

            // 检查资源类型（文件系统或JAR）
            URL resourceUrl = getClass().getResource(resourcePath);

            if (resourceUrl == null) {
                System.err.println("资源目录未找到: " + resourcePath);
                return;
            }

            String protocol = resourceUrl.getProtocol();
            if ("file".equals(protocol)) {
                // 开发环境 - 文件系统
                loadFromFileSystem(resourceUrl);
            } else if ("jar".equals(protocol)) {
                // 生产环境 - JAR包
                loadFromJar(resourceUrl, resourcePath);
            } else {
                System.err.println("不支持的资源协议: " + protocol);
            }
        } catch (IOException | URISyntaxException e) {
            System.err.println("加载资源失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void loadFromFileSystem(URL resourceUrl) throws IOException, URISyntaxException {
        // 文件系统路径
        Path startPath = Paths.get(resourceUrl.toURI());

        Files.walk(startPath)
                .filter(Files::isRegularFile)
                .forEach(path -> {
                    try {
                        String fileName = path.getFileName().toString();
                        if (isImageFile(fileName)) {
                            String key = fileName.substring(0, fileName.lastIndexOf('.'));
                            Image image = ImageIO.read(path.toFile());
                            imageMap.put(key, image);
                        }
                    } catch (IOException e) {
                        System.err.println("加载图片失败: " + path);
                    }
                });
    }

    private void loadFromJar(URL resourceUrl, String resourcePath) throws IOException {
        // 解析JAR文件路径
        String jarPath = resourceUrl.getPath().substring(5, resourceUrl.getPath().indexOf("!"));
        String resourceDir = resourcePath.substring(1); // 去掉开头的斜杠

        try (JarFile jar = new JarFile(jarPath)) {
            Enumeration<JarEntry> entries = jar.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();

                // 检查是否在目标资源目录中
                if (name.startsWith(resourceDir) && !entry.isDirectory() && isImageFile(name)) {
                    try (InputStream is = getClass().getResourceAsStream("/" + name)) {
                        if (is != null) {
                            String fileName = name.substring(name.lastIndexOf('/') + 1);
                            String key = fileName.substring(0, fileName.lastIndexOf('.'));
                            Image image = ImageIO.read(is);
                            imageMap.put(key, image);
                        }
                    }
                }
            }
        }
    }

    private boolean isImageFile(String fileName) {
        String[] extensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp"};
        fileName = fileName.toLowerCase();
        for (String ext : extensions) {
            if (fileName.endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    // 获取图片的方法
    public Image getImage(String name) {
        return imageMap.get(name);
    }
}
